#include "udpsocket.h"

UdpSockets::UdpSockets(QObject *parent) :
    QObject(parent)
{
    m_socket = NULL;
}
UdpSockets::~UdpSockets()
{
    if(m_socket != NULL)
    {
        if(m_socket->isOpen())
        {
            m_socket->close();
        }
        delete m_socket;
        m_socket = NULL;
    }
}


void UdpSockets::initSocket(int port)
{
    m_socket = new QUdpSocket(this);
    m_socket->bind(port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);//端口绑定
    recvMsgBind();
}

QStringList UdpSockets::parseMsg(t_msg msg)
{
    QStringList list;
    list << QString::number(msg.src_id) << QString::number(msg.dst_id) << QString::number(msg.usr_id)
         << QString::number(msg.msg_type, 10) << QString(msg.data);

    return list;
}

//发送的数据位qMsg，发送给ip地址为：recvIp,如果recvIp字段为空，则为广播发送
void UdpSockets::sendMsg(QStringList qMsg, QString recvIp, unsigned port)
{
    QByteArray data;    //字节数组
    QString ports = QString("%1").arg(port);

    for(int i = 0; i < qMsg.length(); ++i)
    {
        data.append(qMsg.at(i).trimmed());
        data.append("$");
    }
    data.append(ports);
    data.append("$client");
    quint16 portsss = port;
    if(recvIp.length() == 0)
        m_socket->writeDatagram(data, data.length(), QHostAddress::Broadcast, portsss);//将data中的数据发送
    else
        m_socket->writeDatagram(data, data.length(), QHostAddress(recvIp), portsss);//将data中的数据发送

}

void UdpSockets::recvMsgBind()
{
    connect(m_socket, SIGNAL(readyRead()),
            this, SLOT(readPendingDatagrams()));//readyRead()信号是每当有新的数据来临时就被触发
}

void UdpSockets::readPendingDatagrams()
{
    m_recvMsg.clear();
    while (m_socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(m_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        m_socket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);
        QStringList tmp = QString(datagram).split("$");
        if(tmp.at(tmp.length() - 1) == "loder")
        {
            m_recvMsg = datagram;
            emit recvData();
        }
    }

}
